<?php
	include_once("global_modules.php");
	
	/**
	 * This function get the list of resources.
	 * @param $filter Array containing ids to be searched.
	 * @param $type String containing the type of resources to be searched (if you want all types, use the default string 'ALL').
	 * @return Array containing a list of resources where each resource has id, type and the resource details (details of channel or node).
	 */
	function get_resources($filter=NULL, $type="ALL"){
		$connection = database_connect();
		
		$resource_types = array('node', 'channel');
		$filter_by_type = "";
		
		if($type != "ALL" && in_array($type, $resource_types))
			$filter_by_type = "WHERE type = '".$type."'";
		
		$query = database_query($connection, "SELECT * FROM resources ".$filter_by_type."");
		
		$resource_list = array();
		$row = 0;
		while($results = database_fetch_object($query, $row)){
			$real_resource_query = database_query($connection, "SELECT * FROM ".$results->type." WHERE id = ".$results->real_resource_id."");
			$resource_details = database_fetch_array($real_resource_query);
			
			$resource_list[] = array(
								'id' => $results->id,
								'type' => $results->type,
								'status' => $results->status,
								'resource_details' => $resource_details
							);
			$row++;
		}
		
		database_close($connection);
		
		if($filter != NULL && is_array($filter))
			$resource_list = filter_LS_list($filter, $resource_list);
		
		return $resource_list;
	}
	
	/**
	 * This function get the list of slices.
	 * @param $filter Array containing ids to be searched.
	 * @return Array containing a list of slices where each slice has id, name, users, resources, status and expiry_date.
	 */
	function get_slices($filter=NULL){
		$connection = database_connect();
		
		$query = database_query($connection, "SELECT * FROM slice");
		
		$slice_list = array();
		$row = 0;
		while($results = database_fetch_object($query, $row)){
			$now = date("Y-m-d H:i:s", time());
			$status_query = database_query($connection, "SELECT * FROM reservation WHERE begin_time <= '".$now."' AND end_time >= '".$now."' AND slice_id = ".$results->id."");
			$status = (database_num_rows($status_query) > 0) ? 'ACTIVE' : 'INACTIVE';
			
			$slice_list[] = array(
								'id' => $results->id,
								'name' => $results->name,
								'users' => get_slice_users($results->id, $connection),
								'resources' => get_slice_resources($results->id, $connection),
								'status' => $status,
								'expiry_date' => $results->expires
							);
			$row++;
		}
		
		database_close($connection);
		
		if($filter != NULL && is_array($filter))
			$slice_list = filter_LS_list($filter, $slice_list);
		
		return $slice_list;
	}
	
	/**
	 * This function return the resource(s) id(s) of a slice.
	 * @param $slice_id Integer containing the slice id.
	 * @param $connection DatabaseConnection containing the open connection to database.
	 * @return Array containing the id list of resources of a slice.
	 */
	function get_slice_resources($slice_id, $connection=NULL){
		$new_connection = ($connection == NULL) ? database_connect() : $connection;
		
		$query = database_query($new_connection, "SELECT resource_id FROM slice_resources WHERE slice_id = ".$slice_id."");
		
		$resource_list = array();
		$row = 0;
		while($results = database_fetch_object($query, $row)){
			$resource_list[] = $results->resource_id;
			$row++;
		}
		
		if($connection == NULL)
			database_close($new_connection);
		
		return $resource_list;
	}
	
	/**
	 * This function return the user(s) id(s) of a slice.
	 * @param $slice_id Integer containing the slice id.
	 * @param $connection DatabaseConnection containing the open connection to database.
	 * @return Array containing the id list of users of a slice.
	 */
	function get_slice_users($slice_id, $connection=NULL){
		$new_connection = ($connection == NULL) ? database_connect() : $connection;
		
		$query = database_query($new_connection, "SELECT user_id FROM slice_users WHERE slice_id = ".$slice_id."");
		
		$user_list = array();
		$row = 0;
		while($results = database_fetch_object($query, $row)){
			$user_list[] = $results->user_id;
			$row++;
		}
		
		if($connection == NULL)
			database_close($new_connection);
		
		return $user_list;
	}
	
	/**
	 * This function return the pxeimages.
	 * @param $filter Array containing ids to be searched.
	 * @return Array containing a list of pxeimages where each pxeimage has id and image_name.
	 */
	function get_pxeimages($filter=NULL){
		$connection = database_connect();
		
		$query = database_query($connection, "SELECT * FROM pxeimages");
		
		$pxeimages_list = array();
		$row = 0;
		while($results = database_fetch_object($query, $row)){
			$pxeimages_list[] = array(
								'id' => $results->id,
								'image_name' => $results->image_name,
								'short_description' => $results->short_description
							);
			$row++;
		}
		
		database_close($connection);
		
		if($filter != NULL && is_array($filter))
			$pxeimages_list = filter_LS_list($filter, $pxeimages_list);
		
		return $pxeimages_list;
	}
	
	/**
	 * This function return the motherboard.
	 * @param $filter Array containing ids to be searched.
	 * @return Array containing a list of motherboards where each motherboard has id and cpu_number.
	 */
	function get_motherboards($filter=NULL){
		$connection = database_connect();
		
		$query = database_query($connection, "SELECT * FROM motherboard");
		
		$motherboards_list = array();
		$row = 0;
		while($results = database_fetch_object($query, $row)){
			$motherboards_list[] = array(
								'id' => $results->id,
								'cpu_type' => $results->cpu_type,
								'cpu_number' => $results->cpu_number,
								'cpu_hz' => $results->cpu_hz,
								'hd_size' => $results->hd_size,
								'memory' => $results->memory
							);
			$row++;
		}
		
		database_close($connection);
		
		if($filter != NULL && is_array($filter))
			$motherboards_list = filter_LS_list($filter, $motherboards_list);
		
		return $motherboards_list;
	}
	
	/**
	 * This function add a resource (node or channel) to database and registers as a resource.
	 * @param $type String informing if the resource type (node or channel).
	 * @param $resource_data Array containing the resource data.
	 * @return boolean TRUE when the resource was successfully added or FALSE when not.
	 */
	function add_resource($type, $resource_data){
		$connection = database_connect();
		
		if($type == "node")
			$query = "INSERT INTO node (control_ip, control_mac, cmc_ip, hostname, hrn, chassis_sn, motherboard_id, pxeimage_id, disk) VALUES ('".$resource_data['control_ip']."', '".$resource_data['control_mac']."', '".$resource_data['cmc_ip']."', '".$resource_data['hostname']."', '".$resource_data['hrn']."', '".$resource_data['chassis_sn']."', ".$resource_data['motherboard_id'].", ".$resource_data['pxeimage_id'].", '".$resource_data['disk']."')";
		else if($type == "channel")
			$query = "INSERT INTO channel (modulation, channel_number, frequency) VALUES ('".$resource_data['modulation']."', '".$resource_data['channel_number']."', '".$resource_data['frequency']."')";
		else
			return FALSE;
		
		$real_resource_insert = database_query($connection, $query);
		
		$query_real_resource_id = database_query($connection, "SELECT id FROM ".$type." ORDER BY id DESC LIMIT 1");
		$real_resource_id = database_fetch_object($query_real_resource_id);
		$real_resource_id = $real_resource_id->id;
		
		$resource_insert = database_query($connection, "INSERT INTO resources (real_resource_id, type) VALUES (".$real_resource_id.", '".$type."')");
		
		database_close($connection);
		
		if($real_resource_insert && $resource_insert)
			return TRUE;
		else
			return FALSE;
	}

	/**
	 * This function add a slice to database.
	 * @param $slice_data Array containing the slice data.
	 * @return Integer containing the id of a new slice when the slice was successfully added or boolean FALSE when not.
	 */
	function add_slice($slice_data, $expire_date=NULL){
		$connection = database_connect();
		
		if($expire_date == NULL)
			$expires = date("Y-m-d H:i:s", time() + (60 * 60 * 24 * 30));
		else
			$expires = $expire_date;
			
		$query = "INSERT INTO slice (name, expires) VALUES ('".$slice_data['name']."', '".$expires."')";
		$slice_insert = database_query($connection, $query);
		
		$query_slice_id = database_query($connection, "SELECT id FROM slice ORDER BY id DESC LIMIT 1");
		$slice_id = database_fetch_object($query_slice_id);
		$slice_id = $slice_id->id;
		
		database_close($connection);
		
		if($slice_insert)
			return $slice_id;
		else
			return FALSE;
	}
	
	/**
	 * This function add a user to slice.
	 * @param $user_id Integer containing the user id.
	 * @param $slice_id Integer containing the slice id.
	 * @return boolean TRUE when the user was successfully added to the slice or FALSE when not. 
	 */
	function add_user_to_slice($user_id, $slice_id){
		$connection = database_connect();
		
		$query = "INSERT INTO slice_users (slice_id, user_id) VALUES (".$slice_id.", ".$user_id.")";
		$su_insert = database_query($connection, $query);
		
		database_close($connection);
		
		if($su_insert)
			return TRUE;
		else
			return FALSE;
	}
	
	/**
	 * This function add a resource to slice.
	 * @param $resource_id Integer containing the resource id.
	 * @param $slice_id Integer containing the slice id.
	 * @return boolean TRUE when the resource was successfully added to the slice or FALSE when not. 
	 */
	function add_resource_to_slice($resource_id, $slice_id){
		$connection = database_connect();
		
		$query = "INSERT INTO slice_resources (slice_id, resource_id) VALUES (".$slice_id.", ".$resource_id.")";
		$rs_insert = database_query($connection, $query);
		
		database_close($connection);
		
		if($rs_insert)
			return TRUE;
		else
			return FALSE;
	}
	
	/**
	 * This function add a pxeimage to database.
	 * @param $pxeimage_data Array containing the pxeimage data.
	 * @return Boolean TRUE if the pxeimage was successfully added or FALSE when not.
	 */
	function add_pxeimage($pxeimage_data){
		$connection = database_connect();
			
		$query = "INSERT INTO pxeimages (image_name, short_description) VALUES ('".$pxeimage_data['image_name']."', '".$pxeimage_data['short_description']."')";
		$pxeimage_insert = database_query($connection, $query);
		
		database_close($connection);
		
		if($pxeimage_insert)
			return TRUE;
		else
			return FALSE;
	}
	
	/**
	 * This function add a motherboard to database.
	 * @param $motherboard_data Array containing the motherboard data.
	 * @return Boolean TRUE if the motherboard was successfully added or FALSE when not.
	 */
	function add_motherboard($motherboard_data){
		$connection = database_connect();
			
		$query = "INSERT INTO motherboard (cpu_type, cpu_number, cpu_hz, hd_size, memory) VALUES ('".$motherboard_data['cpu_type']."', '".$motherboard_data['cpu_number']."', '".$motherboard_data['cpu_hz']."', '".$motherboard_data['hd_size']."', '".$motherboard_data['memory']."')";
		$motherboard_insert = database_query($connection, $query);
		
		database_close($connection);
		
		if($motherboard_insert)
			return TRUE;
		else
			return FALSE;
	}
	
	/**
	 * This function remove a resource (remove in the table channel or node and in the table resources).
	 * @param $resource_id Integer containing the resource id.
	 * @return boolean TRUE when the resource was successfully removed or FALSE when not.
	 */
	function delete_resource($resource_id){
		$connection = database_connect();
		
		$query = database_query($connection, "SELECT * FROM resources WHERE id = ".$resource_id."");
		$resource_data = database_fetch_object($query);
		
		$resource_remove = database_query($connection, "DELETE FROM resources WHERE id = ".$resource_id."");
		$real_resource_remove = database_query($connection, "DELETE FROM ".$resource_data->type." WHERE id = ".$resource_data->real_resource_id."");
		
		database_close($connection);
		
		if($resource_remove && $real_resource_remove)
			return TRUE;
		else
			return FALSE;
	}
	
	/**
	 * This function remove a slice.
	 * @param $slice_id Integer containing the slice id.
	 * @return boolean TRUE when the slice was successfully removed or FALSE when not.
	 */
	function delete_slice($slice_id){
		$connection = database_connect();
		
		$query = "DELETE FROM slice WHERE id = ".$slice_id."";
		$slice_remove = database_query($connection, $query);
		
		database_close($connection);
		
		if($slice_remove)
			return TRUE;
		else
			return FALSE;
	}

	/**
	 * This function remove a user from a slice.
	 * @param $user_id Integer containing the user id.
	 * @param $slice_id Integer containing the slice id.
	 * @return boolean TRUE when the user was successfully removed from a slice or FALSE when not.
	 */
	function delete_user_from_slice($user_id, $slice_id){
		$connection = database_connect();
		
		$query = "DELETE FROM slice_users WHERE slice_id = ".$slice_id." AND user_id = ".$user_id."";
		$su_remove = database_query($connection, $query);
		
		database_close($connection);
		
		if($su_remove)
			return TRUE;
		else
			return FALSE;
	}

	/**
	 * This function remove a resources from a slice.
	 * @param $resource_id Integer containing the resource id.
	 * @param $slice_id Integer containing the slice id.
	 * @return boolean TRUE when the resource was successfully removed from a slice or FALSE when not.
	 */
	function delete_resource_from_slice($resource_id, $slice_id){
		$connection = database_connect();
		
		$query = "DELETE FROM slice_resources WHERE slice_id = ".$slice_id." AND resource_id = ".$resource_id."";
		$rs_remove = database_query($connection, $query);
		
		database_close($connection);
		
		if($rs_remove)
			return TRUE;
		else
			return FALSE;
	}
	
	/**
	 * This function remove a pxeimage.
	 * @param $pxeimage_id Integer containing the pxeimage id.
	 * @return boolean TRUE when the pxeimage was successfully removed or FALSE when not.
	 */
	function delete_pxeimage($pxeimage_id){
		$connection = database_connect();
		
		$query = "DELETE FROM pxeimages WHERE id = ".$pxeimage_id."";
		$pxeimage_remove = database_query($connection, $query);
		
		database_close($connection);
		
		if($pxeimage_remove)
			return TRUE;
		else
			return FALSE;
	}
	
	/**
	 * This function remove a motherboard.
	 * @param $motherboard_id Integer containing the motherboard id.
	 * @return boolean TRUE when the motherboard was successfully removed or FALSE when not.
	 */
	function delete_motherboard($motherboard_id){
		$connection = database_connect();
		
		$query = "DELETE FROM motherboard WHERE id = ".$motherboard_id."";
		$motherboard_remove = database_query($connection, $query);
		
		database_close($connection);
		
		if($motherboard_remove)
			return TRUE;
		else
			return FALSE;
	}
	
	/**
	 * This function update the real resource data (channel or node).
	 * @param $resource_id Integer containing the resource id.
	 * @param $resource_new_data Array containing the new data from real resource.
	 * @return boolean TRUE when the resource was successfully updated or FALSE when not.
	 */
	function update_resource($resource_id, $resource_new_data){
		$connection = database_connect();
		
		$query_resource = database_query($connection, "SELECT * FROM resources WHERE id = ".$resource_id."");
		$real_resource_data = database_fetch_object($query_resource);
		
		$resource_type = $real_resource_data->type;
		$real_resource_id = $real_resource_data->real_resource_id;
		
		$query_update_part = "";
		switch($resource_type){
			case "node":
				$fields = array('control_ip', 'control_mac', 'cmc_ip', 'hostname', 'hrn', 'chassis_sn', 'motherboard_id', 'pxeimage_id', 'disk');
				break;
			case "channel":
				$fields = array('modulation', 'channel_number', 'frequency');
				break;
		}
		
		for($i=0; $i < count($resource_new_data); $i++){
			$array_key_name = array_keys($resource_new_data)[$i];
			
			if(in_array($array_key_name, $fields))
				$query_update_part .= " ".$array_key_name." = '".$resource_new_data[''.$array_key_name.'']."',";
		}
		
		if(empty($query_update_part))
			return FALSE;
			
		if($query_update_part{strlen($query_update_part)-1} == ',')
			$query_update_part = substr($query_update_part, 0, strlen($query_update_part)-1);
			
		if($query_update_part{0} == ' ')
			$query_update_part = substr($query_update_part, 1, strlen($query_update_part)-1);
		
		$query = "UPDATE ".$resource_type." set ".$query_update_part." WHERE id = ".$real_resource_id."";
		$real_resource_update = database_query($connection, $query);
		
		if(isset($resource_new_data['status']) && is_numeric($resource_new_data['status'])){
			$query = "UPDATE resources set status = ".$resource_new_data['status']." WHERE id = ".$resource_id."";
			$update_resource_status = database_query($connection, $query);
		}
		
		database_close($connection);
		
		if($real_resource_update && $update_resource_status)
			return TRUE;
		else
			return FALSE;
	}
	
	/**
	 * This function update the slice name.
	 * @param $slice_id Integer containing the slice id.
	 * @param $name String containing the new slice name.
     * @param $expires String containing the new expires time.
	 * @return boolean TRUE when the slice was successfully updated or FALSE when not.
	 */
	function update_slice($slice_id, $name, $expires){
		$connection = database_connect();
        $update_part = "";
        
        if(!empty($name))
			$update_part .= "name = '".$name."',";
           
		if(!empty($expires))
        	$update_part .= " expires = '".$expires."'";
            
		if(empty($update_part))
			return FALSE;
			
		if($update_part{strlen($update_part)-1} == ',')
			$update_part = substr($update_part, 0, strlen($update_part)-1);
			
		if($update_part{0} == ' ')
			$update_part = substr($update_part, 1, strlen($update_part));
            
		$query = "UPDATE slice SET ".$update_part." WHERE id = ".$slice_id."";
		$update_slice = database_query($connection, $query);

		database_close($connection);
		
		if($update_slice)
			return TRUE;
		else
			return FALSE;
	}
	
	/**
	 * This function update the pxeimage data.
	 * @param $pxeimage_id Integer containing the pxeimage id.
	 * @param $pxeimage_new_data Array containing the pxeimage new data.
	 * @return boolean TRUE when the pxeimage was successfully updated or FALSE when not.
	 */
	function update_pxeimage($pxeimage_id, $pxeimage_new_data){
		$connection = database_connect();
		
		$query = "UPDATE pxeimages SET image_name = '".$pxeimage_new_data['image_name']."', short_description = '".$pxeimage_new_data['short_description']."' WHERE id = ".$pxeimage_id."";
		$update_pxeimage = database_query($connection, $query);

		database_close($connection);
		
		if($update_pxeimage)
			return TRUE;
		else
			return FALSE;
	}
	
	/**
	 * This function update the motherboard data.
	 * @param $motherboard_id Integer containing the motherboard id.
	 * @param $motherboard_new_data Array containing the motherboard new data.
	 * @return boolean TRUE when the motherboard was successfully updated or FALSE when not.
	 */
	function update_motherboard($motherboard_id, $motherboard_new_data){
		$connection = database_connect();
		
		$query = "UPDATE motherboard SET cpu_type = '".$motherboard_new_data['cpu_type']."', cpu_number = '".$motherboard_new_data['cpu_number']."', cpu_hz = '".$motherboard_new_data['cpu_hz']."', hd_size = '".$motherboard_new_data['hd_size']."', memory = '".$motherboard_new_data['memory']."' WHERE id = ".$motherboard_id."";
		$update_motherboard = database_query($connection, $query);

		database_close($connection);
		
		if($update_motherboard)
			return TRUE;
		else
			return FALSE;
	}
?>
